<template>
	<view class="page-body">
		<!-- 页面内容开始 -->

		<!-- 表格搜索组件开始 -->
		<vk-data-table-query v-model="queryForm1.formData" :columns="queryForm1.columns"
			@search="search"></vk-data-table-query>
		<!-- 表格搜索组件结束 -->

		<!-- 自定义按钮区域开始 -->
		<view>
			<el-row>
				<el-button type="success" size="small" @click="exportExcel">导出表格数据</el-button>
			</el-row>
		</view>
		<!-- 自定义按钮区域结束 -->
		<!-- 提示 -->
		<view>
			<div class="notification">*每小时统计一次，统计当天0点累计到前一小时的数据</div>
		</view>
		<!-- 表格组件开始 -->
		<vk-data-table ref="table1" :action="table1.action" :columns="table1.columns" :query-form-param="queryForm1"
			:row-no="true" :pagination="true" stripe="true"  :border="true"
			@current-change="currentChange"></vk-data-table>
		<!-- 表格组件结束 -->
		<view class="page-dialog">
			<!-- 页面弹窗内容开始 -->
			<vk-data-dialog
				v-model="show"
				title="看剧用户数"
				width="900px"
				top="14vh"
				center
				:close-on-click-modal="true"
			>
				<view style="margin: 0 15px;">
					<view class="btn-wrapper">
						<el-button type="primary" @click="exportSelect">导出</el-button>
					</view>
					<view style="display: flex;flex-wrap: wrap;">
						<view class="topbox" v-for="item in detailData" :key="item._id">
							<text style="color: gray;">第{{item.series}}集</text>
							<view class="numstyle">{{item.num}}</view>
							<view style="font-size: 12px; margin-left: 10px;">{{ item.lostRate ? '流失率' + (item.lostRate * 100).toFixed(2)  + '%' : ' ' }}</view>
						</view>
					</view>
				</view>
				<template v-slot:footer>
					<el-button type="primary" @click="show = false">关 闭</el-button>
				</template>
			</vk-data-dialog>
			<!-- 页面弹窗内容开始 -->
		</view>
		<!-- 页面内容结束 -->
	</view>
</template>

<script>
import consoleLog from '../../../uni_modules/vk-unicloud/vk_modules/vk-unicloud-page/libs/install/console.log';
import * as XLSX from 'xlsx';
	var that; // 当前页面对象
	var vk = uni.vk; // vk实例
	var originalForms = {}; // 表单初始化数据

	export default {
		data() {
			// 页面数据变量
			return {
				// 页面是否请求中或加载中
				loading: false,
				// init请求返回的数据
				data: {

				},
				// 表格相关开始 -----------------------------------------------------------
				table1: {
					// 表格数据请求地址
					// action: "api/pub/data/analyzer/getTvAnalyze",
					action: (obj={})=>{
						let {
							data, // 请求数据
							success, // 成功回调
							fail, // 失败回调
							complete, // 成功回调
						} = obj;
						// 发起http请求
						vk.callFunction({
							name: 'leyouyinghua',
							url: `api/pub/data/analyzer/getTvAnalyze`,
							data: data,
							success: (res) => {
								if (typeof success === "function") {
									success({
										rows: res.rows, // 列表数据
										total: res.total, // 总记录数（如果没有总记录数，则需要返回getCount和hasMore）
										getCount: res.getCount, // 是否执行了count请求，当total的值不是总记录数时需要返回 getCount: false
										hasMore: res.hasMore, // 是否还有下一页，当total的值不是总记录数时需要返回是否还有下一页
									});
								}
							},
							fail: (res) => {
								if (typeof fail === "function") fail(res);
							},
							complete: (res) => {
								if (typeof complete === "function") complete(res);
							}
						});
					},
					// 表格字段显示规则
					columns: [
						// {"key":"_id","title":"ID","type":"text","width":200},
						{
							"key": "date",
							"title": "日期",
							"type": "text",
							"width": 200
						},
						{
							"key": "tv_name",
							"title": "短剧名称",
							"type": "text",
							"width": 200
						},
						// {
						// 	"key": "tf_type",
						// 	"title": "投放类型",
						// 	"type": "text",
						// 	"width": 200
						// },
						{
							"key": "total_recharge_income",
							"title": "充值总收入",
							"type": "text",
							"width": 200
						},
						{
							"key": "member_count",
							"title": "会员笔数",
							"type": "text",
							"width": 200
						},
						{
							"key": "member_amount",
							"title": "会员金额",
							"type": "text",
							"width": 200
						},
						{
							"key": "full_series_purchase_count",
							"title": "整剧购买数",
							"type": "text",
							"width": 200
						},
						{
							"key": "full_series_purchase_amount",
							"title": "整剧购买金额",
							"type": "text",
							"width": 200
						},
						{
							"key": "total_viewer_count",
							"title": "看剧用户总数",
							"type": "text",
							"width": 200,
							"buttons": [
								{
									title: "详情",
									type: "text",
									mode: "default",
									show: ["detail", "row"],
									click: (options) => {
										that.detailData = [];
										console.log(2, options.value, options.formData);
										that.show = true;
										that.detailData = options.formData.series_view_user_num;
										// vk.callFunction({
										// 	url: 'api/pub/data/analyzer/getTvUserLookNumAnalyze',
										// 	data: {
										// 		tv_id: options.formData.tv_id,
										// 		date: options.formData.date
										// 	},
										// 	success: (data) => {
										// 		that.detailData = data.rows;
										// 		// 通知组件操作成功（否则组件按钮会一直处于loading状态）
										// 		options.success({
										// 			msg: ""
										// 		});
										// 	}
										// });
									}
								}
							]
						},
					],
					// 多选框选中的值
					multipleSelection: [],
					// 当前高亮的记录
					selectItem: ""
				},
				// 表格相关结束 -----------------------------------------------------------
				// 表单相关开始 -----------------------------------------------------------
				// 查询表单请求数据
				queryForm1: {
					// 查询表单数据源，可在此设置默认值
					formData: {
						
					},
					// 查询表单的字段规则 fieldName:指定数据库字段名,不填默认等于key
					columns: [
						{
							"key": "tv_name",
							"title": "短剧名称",
							"type": "text",
							"width": 200,
							"mode": "%%"
						},
						{
							"key": "date_time",
							"title": "时间",
							"type": "datetimerange",
							"width": 400,
							"mode": "[]"
						}
					]
				},
				form1: {},
				// 其他弹窗表单
				formDatas: {},
				show: false,
				detailData: [],
				// 表单相关结束 -----------------------------------------------------------
			};
		},
		// 监听 - 页面每次【加载时】执行(如：前进)
		onLoad(options = {}) {
			that = this;
			vk = that.vk;
			that.options = options;
			that.init(options);
		},
		// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
		onReady() {},
		// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
		onShow() {},
		// 监听 - 页面每次【隐藏时】执行(如：返回)
		onHide() {},
		// 函数
		methods: {
			// 页面数据初始化函数
			init(options) {
				console.log('initform1',that.form1)
				originalForms["form1"] = vk.pubfn.copyObject(that.form1);
			},
			// 页面跳转
			pageTo(path) {
				vk.navigateTo(path);
			},
			// 表单重置
			resetForm() {
				vk.pubfn.resetForm(originalForms, that);
			},
			// 搜索
			search() {
				console.log('search',that.$refs.table1)
				that.$refs.table1.search();
			},
			// 刷新
			refresh() {
				that.$refs.table1.refresh();
			},
			// 获取当前选中的行的数据
			getCurrentRow() {
				return that.$refs.table1.getCurrentRow();
			},
			// 监听 - 行的选中高亮事件
			currentChange(val) {
				that.table1.selectItem = val;
			},
			// 当选择项发生变化时会触发该事件
			selectionChange(list) {
				that.table1.multipleSelection = list;
			},
			// 到处表格数据
			exportExcel() {
				that.$refs.table1.exportExcel({
				  fileName: "短剧数据",
				  title: "正在导出数据...",
				  pageIndex: 1,
				  pageSize: -1, // 此值为-1，代表导出所有数据
				});
			},
			exportSelect() {
			//  导出选中
			    this.$confirm("是否确认导出当前所有数据?", "警告", {
			        confirmButtonText: "确定",
			        cancelButtonText: "取消",
			        type: "warning",
			    }).then((response) => {
			        let tableData = [
			            ['序号', '第几集', '看剧用户数', '流失率']//导出表头
			        ] // 表格表头
			        this.detailData.forEach((item, index) => {
			            let rowData = []
			            //导出内容的字段
			            rowData = [
							index + 1,
							`第${item.series}集`,
							item.num,
							item.lostRate ? (item.lostRate * 100).toFixed(2) + '%' : '--',
			            ]
			            tableData.push(rowData)
					})
			        let workSheet = XLSX.utils.aoa_to_sheet(tableData);
			        let bookNew = XLSX.utils.book_new();
			        XLSX.utils.book_append_sheet(bookNew, workSheet, '看剧用户数') // 工作簿名称
			        let name = '看剧用户数' + this.timeFormat() + '.xlsx'
			        XLSX.writeFile(bookNew, name) // 保存的文件名
			    })
			},
			timeFormat() {
				let time = new Date();
				let year = time.getFullYear();
				let month = time.getMonth() + 1;
				let date = time.getDate();
				let hours = time.getHours();
				let minutes = time.getMinutes();
				let seconds = time.getSeconds();
				return year + '-' + this.addZero(month) + '-' + this.addZero(date) + ' ' + this.addZero(hours) + ':' + this.addZero(minutes) + ':' + this.addZero(seconds);
			},
			addZero(num) {
				return num < 10 ? '0' + num : num
			},
		},
		// 监听属性
		watch: {

		},
		// 过滤器
		filters: {

		},
		// 计算属性
		computed: {

		}
	};
</script>
<style lang="scss" scoped>
	.page-body {}
	page {
		background-color: #f5f5f5;
	}
	
	.topbox {
		width: 13%;
		height: 50px;
		font-size: 18px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		box-shadow: 0 4rpx 8rpx 0 rgba(0, 0, 0, 0.2), 0 6rpx 20rpx 0 rgba(0, 0, 0, 0);
		margin: 10px;
		padding: 15px;
		border-radius: 10rpx;
		background-color: #fff;
	}
	
	.numstyle {
		font-size: 20px;
		color: #409eff;
		font-weight: bold;
	}
	.m-flex {
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.notification {
		margin-top: 10px;
		color: grey;
		font-size: 12px;
	}
	.btn-wrapper {
		position: absolute;
		top: 10px;
		right: 50px;
		display: flex;
		flex-direction: row-reverse;
	}
</style>